import React, { useState, Dispatch, SetStateAction } from 'react';
import store from '@/store';
import { Form, Input, Button, Row, Col, message } from 'antd';
import { Link, useHistory } from 'ice';
import panda from './images/panda.jpg';
import { postCaptcha, register } from './service';
import styles from './index.module.scss';
import { useInterval } from 'ahooks';

function CountDown({ setIsSendCode }: { setIsSendCode: Dispatch<SetStateAction<boolean>> }) {
  const [count, setCount] = useState(50);
  useInterval(() => {
    if (count > 0) {
      setCount(count - 1);
    } else {
      setIsSendCode(false);
    }
  }, 1000);
  return <div>{count}</div>;
}

function SignIn() {
  const [isSendCode, setIsSendCode] = useState<boolean>(false);
  const [form] = Form.useForm();
  const history = useHistory();
  const postCode = async () => {
    if (form.getFieldValue('email')) {
      await postCaptcha({ email: form.getFieldValue('email') });
      setIsSendCode(true);
      message.success('验证码已发送');
    } else {
      message.warning('请输入邮箱');
    }
  };
  return (
    <Row className={styles.signIn} style={{ width: '100%', marginBottom: 20 }} justify="center" align="middle">
      <Col span={10} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <img src={panda} alt="" style={{ width: '80%', maxWidth: 370 }} />
      </Col>
      <Col span={10}>
        <div style={{ fontSize: 25, fontWeight: 550, marginBottom: 50, marginTop: 30 }}>注册</div>
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          onFinish={async (values) => {
            await register(values);
            message.success('注册成功,请登录');
            history.push('/login');
          }}
        >
          <Form.Item label="" name="username" rules={[{ required: true, message: '请输入昵称' }]}>
            <Input placeholder="昵称" />
          </Form.Item>
          <Form.Item
            label=""
            name="email"
            rules={[
              {
                type: 'email',
                message: '请输入正确的邮箱',
              },
              { required: true, message: '请输入邮箱' },
            ]}
          >
            <Input placeholder="邮箱" />
          </Form.Item>
          <Form.Item label="" name="captcha" rules={[{ required: true, message: '请输入密码' }]}>
            <Input
              placeholder="验证码"
              addonAfter={
                <>
                  {isSendCode ? (
                    <Button type="primary" size="small" style={{ height: 30, minWidth: 112 }} disabled>
                      <div style={{ display: 'flex', justifyContent: 'center' }}>
                        <CountDown setIsSendCode={setIsSendCode} /> <span>s 后重新发送</span>
                      </div>
                    </Button>
                  ) : (
                    <Button type="primary" size="small" style={{ height: 30 }} onClick={postCode}>
                      发送验证码
                    </Button>
                  )}
                </>
              }
            />
          </Form.Item>
          <Form.Item
            label=""
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { type: 'string', min: 6, message: '密码长度不得小于6位', validateTrigger: 'onBlur' },
            ]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item
            label=""
            name="password_confirm"
            rules={[
              { required: true, message: '请确认密码' },
              { type: 'string', min: 6, message: '密码长度不得小于6位', validateTrigger: 'onBlur' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('密码必须一样'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="确认密码" />
          </Form.Item>
          <div style={{ marginBottom: 20 }}>
            <Link style={{ color: '#a9a9a9' }} to="/login">
              已有账号？马上登录
            </Link>
          </div>

          <Form.Item wrapperCol={{ span: 18 }}>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              确认
            </Button>
          </Form.Item>
        </Form>
      </Col>
    </Row>
  );
}

export default SignIn;
